﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ShiNiu.Memcahce
{
    public static class JsonExtensions
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Data"></param>
        /// <param name="isJs">是否为前端js。如果是 data为null的时候返回 null </param>
        /// <returns></returns>
        public static string ToJson(this object Data, bool isJs = false)
        {
            if (isJs && Data == null)
                return isJs ? "null" : "";

            if (Data == null)
                return "";

            IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
            timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";

            var settings = new JsonSerializerSettings()
            {
                Converters = new List<JsonConverter>() { new LongConverter(), timeFormat, },
            };

            return JsonConvert.SerializeObject(Data, settings);
        }


        public static T Deserialize<T>(this string Data)
        {
            if (string.IsNullOrWhiteSpace(Data))
                return default(T);

            return JsonConvert.DeserializeObject<T>(Data);
        }


    }


    public class LongConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(long);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            return long.Parse(reader.Value.ToString());
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            writer.WriteValue(value.ToString());
        }
    }
}
